package com.chinasoft.carWithuserservice.controller;


import com.chinasoft.carWithuserservice.service.CarWithUserService;
import com.chinasoft.carWithuserservice.utils.JwtUtils;
import com.chinasoft.ms.dto.CarWithUserDTO;
import com.chinasoft.ms.pojo.Result;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/api/carWithuser")
@RestController
public class CarWithUserController {
    @Autowired
    CarWithUserService carWithUserService;

    @PostMapping("/number/{pageNum}/size/{pageSize}")
    public Result<PageInfo<CarWithUserDTO>> queryByPage(
            @PathVariable Integer pageNum,
            @PathVariable Integer pageSize,
            @RequestBody CarWithUserDTO query,
            HttpServletRequest request) {

        // 从token中获取当前用户ID（假设你使用JWT）
        String token = request.getHeader("authorization");
        Long userId = Long.valueOf(JwtUtils.getAudience(token));
        System.out.println("userId:"+userId);
        // 如果是普通用户，只查询自己的数据
        if (carWithUserService.getRoleUserWithId(userId) == 2) {
            query.setUserId(userId);
        }
        System.out.println("query:"+carWithUserService.getRoleUserWithId(userId));
        PageInfo<CarWithUserDTO> pageInfo = carWithUserService.queryByPage(
                pageNum, pageSize, query.getCarId(), query.getUserId());
        return  new Result<>(200, "Success", pageInfo);
    }

    @PostMapping
    public Result<Integer> update(@RequestBody CarWithUserDTO carWithUser) {
        int result = carWithUserService.update(carWithUser);
        return new Result<>(200, "Success", result);
    }

    @PostMapping("/deleteRecord")
    public Result<Integer> deleteRecord(@RequestBody CarWithUserDTO carWithUser) {
        int result = carWithUserService.deleteById(carWithUser.getId());
        return new Result<>(200, "Success", result);
    }
}
